/**
  ******************************************************************************
  * @file    main.c
  * @author  AE Team
  * @version 1.0.3
  * @date    2024-05-28
  * @brief   本样例演示UART1作为LIN的主机和从机进行通信
  *          主机发送随机的8字节数据给从机，紧接着读回上一帧发送的8字节数据
  *          通过UART2向PC打印LOG信息
  *
  * @note    硬件平台：SYM32L010_StartKit_V1.0
  *          接线说明：短接J13
  *                    断开J12、J23、J19
  *
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2024 SIYIMicro.
  * All rights reserved.</center></h2>
  *
  *
  ******************************************************************************
  */


/******************************************************************************/
/* Include files                                                              */
/******************************************************************************/
#include "main.h"
#include "sym32l010_hal_sysctrl.h"
#include "sym32l010_hal_systick.h"
#include "sym32l010_hal_gpio.h"
#include "sym32l010_hal_uart.h"
#include "sym32l010_startkit_board.h"

#include "stdlib.h"
#include "lin.h"

/******************************************************************************/
/* Local pre-processor symbols/macros ('#define')                             */
/******************************************************************************/
#define UART_LIN    SYM_UART1

/******************************************************************************/
/* Global variable definitions (declared in header file with 'extern')        */
/******************************************************************************/
UART_HandleTypeDef hUart;
/******************************************************************************/
/* Local type definitions ('typedef')                                         */
/******************************************************************************/

/******************************************************************************/
/* Local function prototypes ('static')                                       */
/******************************************************************************/
static void LIN_Port_Init(void);

/******************************************************************************/
/* Local variable definitions ('static')                                      */
/******************************************************************************/

/******************************************************************************/
/* Local pre-processor symbols/macros ('#define')                             */
/******************************************************************************/

/******************************************************************************/
/* Function implementation - global ('extern') and local ('static')           */
/******************************************************************************/


/*******************************************************************************
 ** \brief  Main function of project
 **
 ** \return uint32_t return value, if needed
 **
 **
 ******************************************************************************/
int32_t main(void)
{
    uint32_t    Times = 0;
    uint8_t     i, Id, PId, CheckSum = 0, CalcCheckSum = 0;
    LIN_ErrCodeTypeDef ErrCode = LIN_ERR_NONE;

    MemClr(&hUart, sizeof(hUart));

    // 使能外设时钟
    HAL_SYSCTRL_UART1_CLK_ENABLE();                                   // UART1作为LIN传输
    HAL_SYSCTRL_UART2_CLK_ENABLE();                                   // UART2作为UART向PC打印Log

    // 配置HSI时钟
    HAL_SysCtrl_HSI_SetDiv(HSIOSC_TO_HSI8MHZ);

    // 初始化SysTick
    HAL_InitTick(8000000);

    Bsp_Led_Init();

    // 初始化板载UART打印
    Bsp_Uart_Init(8000000, 115200);
    printf("Print(Uart2) Init.\r\n");

    // Init UART_LIN As LIN Mode
    LIN_Port_Init();
    hUart.Instance = UART_LIN;
    hUart.Init.PclkFreq = 8000000;
    hUart.Init.BaudRate = 20000;
    HAL_UART_Init(&hUart);
    HAL_UART_TXD_Enable(hUart.Instance);
    HAL_UART_RXD_Enable(hUart.Instance);
    HAL_LIN_Enable(hUart.Instance, LIN_BRKLEN_11BIT);
    printf("LIN(Uart1) Init\r\n");

    while (1)
    {
        Times++;                                                      // 奇数代表主机要发送数据，偶数代表主机要接收数据
        printf("LIN Work Times = %d\r\n", Times);

        Id = (Times%2) ? 0x05 : 0x16;                                 // 设置ID，奇数时ID = 0x05, 偶数时ID = 0x16
        PId = LIN_CalcPID(Id);                                        // 根据ID计算出PID

        if (Times%2)                                                  // 向发送BUFF填充8个随机数
        {
            for (i = 0; i < DATA_LEN; i++)
            {
                UserSendBuf[i] = rand()&0xFF;
            }
        }

        /*******************帧头：主机发送帧头**************************/
        LIN_SendBreak_Polling(&hUart, 13, 1);                         // 主机发送间隔段(长度13bit)并等待1bit时间长度的字节间间隔
        printf("LIN Send Break\r\n");
        LIN_SendSync_Polling(&hUart, 2);                              // 主机发送同步码并等待2bit时间长度的字节间间隔
        printf("LIN Send sync\r\n");
        LIN_SendData_Polling(&hUart, &PId, 1, 0);                     // 主机发送PID
        printf("LIN Send Pid\r\n");

        /*******************应答：1.主机发送8字节应答*******************/
        if (Times%2)
        {
            LIN_Delay_nBit(&hUart, 2);                                // 等待2Bit时间用来让从机协议有足够的响应时间

            LIN_SendData_Polling(&hUart, UserSendBuf, DATA_LEN, 0);   // 主机发送8字节数据，字节间不等待

            CheckSum = LIN_CalcCheckSum(UserSendBuf, DATA_LEN);       // 计算要发送数据的校验和

            CheckSum = ~CheckSum;

            LIN_SendData_Polling(&hUart, &CheckSum, 1, 0);            // 主机发送1字节校验和

            LIN_Delay_nBit(&hUart, 10);
        }

        /*******************应答：2.主机接收8字节应答*******************/
        else
        {
            do {
                ErrCode = LIN_ERR_NONE;

                if (LIN_RecvData_Polling(&hUart, UserRecvBuf, DATA_LEN, 200) != HAL_OK) // 主机接收8字节数据
                {
                    ErrCode = LIN_ERR_RECVDATA;                       // 出错则直接结束
                    break;
                }

                if (LIN_RecvData_Polling(&hUart, &CheckSum, 1, 10) != HAL_OK) // 主机接收校验和
                {
                    ErrCode = LIN_ERR_RECVSUM;
                    break;
                }

                CalcCheckSum = LIN_CalcCheckSum(UserRecvBuf, DATA_LEN);
                if ((CalcCheckSum + CheckSum) != 0xFF)                // 计算出的校验和+接收到的校验和应该等于0xFF
                {
                    ErrCode = LIN_ERR_CHECKSUM;
                    break;
                }

                /*******************User Compare****************************/
                for(i = 0; i < DATA_LEN; i++)
                {
                    if (UserSendBuf[i] != UserRecvBuf[i])
                    {
                        ErrCode = LIN_ERR_COMPARE;
                        break;
                    }
                }

                LIN_Delay_nBit(&hUart, 10);

            } while (0);
        }


        /*******************log：结束一次收发传输，打印log*******************/
        if (Times%2 == 0)
        {
            printf("  SendBuff = ");
            for (i = 0; i < DATA_LEN; i++)
            {
                printf("0x%2x ", UserSendBuf[i]);
            }
            printf("\r\n");

            printf("  RecvBuff = ");
            for (i = 0; i < DATA_LEN; i++)
            {
                printf("0x%2x ", UserRecvBuf[i]);
            }
            printf("\r\n");

            printf("%s, Work Status = %d\r\n\r\n", (ErrCode==LIN_ERR_NONE) ? "PASS" : "FAIL", ErrCode);

            HAL_Delay(2);
        }
    }
}


/*******************************************************************************
 * @brief  LIN 端口初始化
 * @param  None
 * @retval None
 * @note
 */
static void LIN_Port_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;

    MemClr(&GPIO_InitStruct, sizeof(GPIO_InitStruct));

    HAL_SYSCTRL_GPIOA_CLK_ENABLE();

    // Config PA06 AS UART1.TXD <--> LIN
    GPIO_InitStruct.Pins = GPIO_PIN_6;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    HAL_GPIO_Init(SYM_GPIOA, &GPIO_InitStruct);
    AFx_UART1TXD_PA06();

    // Config PA05 AS UART1.RXD <--> LIN
    GPIO_InitStruct.Pins = GPIO_PIN_5;
    GPIO_InitStruct.Pull = GPIO_PULL_UP;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    HAL_GPIO_Init(SYM_GPIOA, &GPIO_InitStruct);
    AFx_UART1RXD_PA05();
}


/*******************************************************************************
 ** EOF (not truncated)
 ******************************************************************************/
#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
    /* USER CODE BEGIN */
    /* User can add his own implementation to report the file name and line number,
       tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
    /* USER CODE END */
}
#endif /* USE_FULL_ASSERT */


/************************ (C) COPYRIGHT SIYIMicro *****END OF FILE*************/
